4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
22 use MediaWiki\MediaWikiServices
;
23 use MediaWiki\Revision\MutableRevisionRecord
;
24 use MediaWiki\Revision\RevisionRecord
;
25 use MediaWiki\Revision\RevisionArchiveRecord
;
26 use MediaWiki\Revision\RevisionStore
;
27 use MediaWiki\Revision\SlotRecord
;
29 class ApiComparePages
extends ApiBase
{
31 /** @var RevisionStore */
32 private $revisionStore;
34 /** @var \MediaWiki\Revision\SlotRoleRegistry */
35 private $slotRoleRegistry;
37 private $guessedTitle = false, $props;
39 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
40 parent
::__construct( $mainModule, $moduleName, $modulePrefix );
41 $this->revisionStore
= MediaWikiServices
::getInstance()->getRevisionStore();
42 $this->slotRoleRegistry
= MediaWikiServices
::getInstance()->getSlotRoleRegistry();
45 public function execute() {
46 $params = $this->extractRequestParams();
48 // Parameter validation
49 $this->requireAtLeastOneParameter(
50 $params, 'fromtitle', 'fromid', 'fromrev', 'fromtext', 'fromslots'
52 $this->requireAtLeastOneParameter(
53 $params, 'totitle', 'toid', 'torev', 'totext', 'torelative', 'toslots'
56 $this->props
= array_flip( $params['prop'] );
58 // Cache responses publicly by default. This may be overridden later.
59 $this->getMain()->setCacheMode( 'public' );
61 // Get the 'from' RevisionRecord
62 list( $fromRev, $fromRelRev, $fromValsRev ) = $this->getDiffRevision( 'from', $params );
64 // Get the 'to' RevisionRecord
65 if ( $params['torelative'] !== null ) {
67 $this->dieWithError( 'apierror-compare-relative-to-nothing' );
69 if ( $params['torelative'] !== 'cur' && $fromRelRev instanceof RevisionArchiveRecord
) {
70 // RevisionStore's getPreviousRevision/getNextRevision blow up
71 // when passed an RevisionArchiveRecord for a deleted page
72 $this->dieWithError( [ 'apierror-compare-relative-to-deleted', $params['torelative'] ] );
74 switch ( $params['torelative'] ) {
76 // Swap 'from' and 'to'
77 list( $toRev, $toRelRev, $toValsRev ) = [ $fromRev, $fromRelRev, $fromValsRev ];
78 $fromRev = $this->revisionStore
->getPreviousRevision( $toRelRev );
79 $fromRelRev = $fromRev;
80 $fromValsRev = $fromRev;
82 $title = Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() );
84 'apiwarn-compare-no-prev',
85 wfEscapeWikiText( $title->getPrefixedText() ),
89 // (T203433) Create an empty dummy revision as the "previous".
90 // The main slot has to exist, the rest will be handled by DifferenceEngine.
91 $fromRev = $this->revisionStore
->newMutableRevisionFromArray( [
92 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
96 $toRelRev->getContent( SlotRecord
::MAIN
, RevisionRecord
::RAW
)
104 $toRev = $this->revisionStore
->getNextRevision( $fromRelRev );
108 $title = Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() );
110 'apiwarn-compare-no-next',
111 wfEscapeWikiText( $title->getPrefixedText() ),
115 // (T203433) The web UI treats "next" as "cur" in this case.
116 // Avoid repeating metadata by making a MutableRevisionRecord with no changes.
117 $toRev = MutableRevisionRecord
::newFromParentRevision( $fromRelRev );
122 $title = $fromRelRev->getPageAsLinkTarget();
123 $toRev = $this->revisionStore
->getRevisionByTitle( $title );
125 $title = Title
::newFromLinkTarget( $title );
127 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
135 list( $toRev, $toRelRev, $toValsRev ) = $this->getDiffRevision( 'to', $params );
138 // Handle missing from or to revisions (should never happen)
139 // @codeCoverageIgnoreStart
140 if ( !$fromRev ||
!$toRev ) {
141 $this->dieWithError( 'apierror-baddiff' );
143 // @codeCoverageIgnoreEnd
146 if ( !$fromRev->audienceCan(
147 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
149 $this->dieWithError( [ 'apierror-missingcontent-revid', $fromRev->getId() ], 'missingcontent' );
151 if ( !$toRev->audienceCan(
152 RevisionRecord
::DELETED_TEXT
, RevisionRecord
::FOR_THIS_USER
, $this->getUser()
154 $this->dieWithError( [ 'apierror-missingcontent-revid', $toRev->getId() ], 'missingcontent' );
158 $context = new DerivativeContext( $this->getContext() );
159 if ( $fromRelRev && $fromRelRev->getPageAsLinkTarget() ) {
160 $context->setTitle( Title
::newFromLinkTarget( $fromRelRev->getPageAsLinkTarget() ) );
161 } elseif ( $toRelRev && $toRelRev->getPageAsLinkTarget() ) {
162 $context->setTitle( Title
::newFromLinkTarget( $toRelRev->getPageAsLinkTarget() ) );
164 $guessedTitle = $this->guessTitle();
165 if ( $guessedTitle ) {
166 $context->setTitle( $guessedTitle );
169 $de = new DifferenceEngine( $context );
170 $de->setRevisions( $fromRev, $toRev );
171 if ( $params['slots'] === null ) {
172 $difftext = $de->getDiffBody();
173 if ( $difftext === false ) {
174 $this->dieWithError( 'apierror-baddiff' );
178 foreach ( $params['slots'] as $role ) {
179 $difftext[$role] = $de->getDiffBodyForRole( $role );
183 // Fill in the response
185 $this->setVals( $vals, 'from', $fromValsRev );
186 $this->setVals( $vals, 'to', $toValsRev );
188 if ( isset( $this->props
['rel'] ) ) {
189 if ( !$fromRev instanceof MutableRevisionRecord
) {
190 $rev = $this->revisionStore
->getPreviousRevision( $fromRev );
192 $vals['prev'] = $rev->getId();
195 if ( !$toRev instanceof MutableRevisionRecord
) {
196 $rev = $this->revisionStore
->getNextRevision( $toRev );
198 $vals['next'] = $rev->getId();
203 if ( isset( $this->props
['diffsize'] ) ) {
204 $vals['diffsize'] = 0;
205 foreach ( (array)$difftext as $text ) {
206 $vals['diffsize'] +
= strlen( $text );
209 if ( isset( $this->props
['diff'] ) ) {
210 if ( is_array( $difftext ) ) {
211 ApiResult
::setArrayType( $difftext, 'kvp', 'diff' );
212 $vals['bodies'] = $difftext;
214 ApiResult
::setContentValue( $vals, 'body', $difftext );
218 // Diffs can be really big and there's little point in having
219 // ApiResult truncate it to an empty response since the diff is the
220 // whole reason this module exists. So pass NO_SIZE_CHECK here.
221 $this->getResult()->addValue( null, $this->getModuleName(), $vals, ApiResult
::NO_SIZE_CHECK
);
225 * Load a revision by ID
227 * Falls back to checking the archive table if appropriate.
230 * @return RevisionRecord|null
232 private function getRevisionById( $id ) {
233 $rev = $this->revisionStore
->getRevisionById( $id );
234 if ( !$rev && $this->getUser()->isAllowedAny( 'deletedtext', 'undelete' ) ) {
235 // Try the 'archive' table
236 $arQuery = $this->revisionStore
->getArchiveQueryInfo();
237 $row = $this->getDB()->selectRow(
241 [ 'ar_namespace', 'ar_title' ]
243 [ 'ar_rev_id' => $id ],
249 $rev = $this->revisionStore
->newRevisionFromArchiveRow( $row );
250 $rev->isArchive
= true;
257 * Guess an appropriate default Title for this request
261 private function guessTitle() {
262 if ( $this->guessedTitle
!== false ) {
263 return $this->guessedTitle
;
266 $this->guessedTitle
= null;
267 $params = $this->extractRequestParams();
269 foreach ( [ 'from', 'to' ] as $prefix ) {
270 if ( $params["{$prefix}rev"] !== null ) {
271 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
273 $this->guessedTitle
= Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
278 if ( $params["{$prefix}title"] !== null ) {
279 $title = Title
::newFromText( $params["{$prefix}title"] );
280 if ( $title && !$title->isExternal() ) {
281 $this->guessedTitle
= $title;
286 if ( $params["{$prefix}id"] !== null ) {
287 $title = Title
::newFromID( $params["{$prefix}id"] );
289 $this->guessedTitle
= $title;
295 return $this->guessedTitle
;
299 * Guess an appropriate default content model for this request
300 * @param string $role Slot for which to guess the model
301 * @return string|null Guessed content model
303 private function guessModel( $role ) {
304 $params = $this->extractRequestParams();
307 foreach ( [ 'from', 'to' ] as $prefix ) {
308 if ( $params["{$prefix}rev"] !== null ) {
309 $rev = $this->getRevisionById( $params["{$prefix}rev"] );
311 if ( $rev->hasSlot( $role ) ) {
312 return $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
318 $guessedTitle = $this->guessTitle();
319 if ( $guessedTitle ) {
320 return $this->slotRoleRegistry
->getRoleHandler( $role )->getDefaultModel( $guessedTitle );
323 if ( isset( $params["fromcontentmodel-$role"] ) ) {
324 return $params["fromcontentmodel-$role"];
326 if ( isset( $params["tocontentmodel-$role"] ) ) {
327 return $params["tocontentmodel-$role"];
330 if ( $role === SlotRecord
::MAIN
) {
331 if ( isset( $params['fromcontentmodel'] ) ) {
332 return $params['fromcontentmodel'];
334 if ( isset( $params['tocontentmodel'] ) ) {
335 return $params['tocontentmodel'];
343 * Get the RevisionRecord for one side of the diff
345 * This uses the appropriate set of parameters to determine what content
348 * Returns three values:
349 * - A RevisionRecord holding the content
350 * - The revision specified, if any, even if content was supplied
351 * - The revision to pass to setVals(), if any
353 * @param string $prefix 'from' or 'to'
354 * @param array $params
355 * @return array [ RevisionRecord|null, RevisionRecord|null, RevisionRecord|null ]
357 private function getDiffRevision( $prefix, array $params ) {
358 // Back compat params
359 $this->requireMaxOneParameter( $params, "{$prefix}text", "{$prefix}slots" );
360 $this->requireMaxOneParameter( $params, "{$prefix}section", "{$prefix}slots" );
361 if ( $params["{$prefix}text"] !== null ) {
362 $params["{$prefix}slots"] = [ SlotRecord
::MAIN
];
363 $params["{$prefix}text-main"] = $params["{$prefix}text"];
364 $params["{$prefix}section-main"] = null;
365 $params["{$prefix}contentmodel-main"] = $params["{$prefix}contentmodel"];
366 $params["{$prefix}contentformat-main"] = $params["{$prefix}contentformat"];
371 $suppliedContent = $params["{$prefix}slots"] !== null;
373 // Get the revision and title, if applicable
375 if ( $params["{$prefix}rev"] !== null ) {
376 $revId = $params["{$prefix}rev"];
377 } elseif ( $params["{$prefix}title"] !== null ||
$params["{$prefix}id"] !== null ) {
378 if ( $params["{$prefix}title"] !== null ) {
379 $title = Title
::newFromText( $params["{$prefix}title"] );
380 if ( !$title ||
$title->isExternal() ) {
382 [ 'apierror-invalidtitle', wfEscapeWikiText( $params["{$prefix}title"] ) ]
386 $title = Title
::newFromID( $params["{$prefix}id"] );
388 $this->dieWithError( [ 'apierror-nosuchpageid', $params["{$prefix}id"] ] );
391 $revId = $title->getLatestRevID();
394 // Only die here if we're not using supplied text
395 if ( !$suppliedContent ) {
396 if ( $title->exists() ) {
398 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ], 'nosuchrevid'
402 [ 'apierror-missingtitle-byname', wfEscapeWikiText( $title->getPrefixedText() ) ],
409 if ( $revId !== null ) {
410 $rev = $this->getRevisionById( $revId );
412 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ] );
414 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
416 // If we don't have supplied content, return here. Otherwise,
417 // continue on below with the supplied content.
418 if ( !$suppliedContent ) {
421 // Deprecated 'fromsection'/'tosection'
422 if ( isset( $params["{$prefix}section"] ) ) {
423 $section = $params["{$prefix}section"];
424 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
425 $content = $rev->getContent( SlotRecord
::MAIN
, RevisionRecord
::FOR_THIS_USER
,
429 [ 'apierror-missingcontent-revid-role', $rev->getId(), SlotRecord
::MAIN
], 'missingcontent'
432 $content = $content ?
$content->getSection( $section ) : null;
435 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
436 "nosuch{$prefix}section"
439 $newRev->setContent( SlotRecord
::MAIN
, $content );
442 return [ $newRev, $rev, $rev ];
446 // Override $content based on supplied text
448 $title = $this->guessTitle();
451 $newRev = MutableRevisionRecord
::newFromParentRevision( $rev );
453 $newRev = $this->revisionStore
->newMutableRevisionFromArray( [
454 'title' => $title ?
: Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
)
457 foreach ( $params["{$prefix}slots"] as $role ) {
458 $text = $params["{$prefix}text-{$role}"];
459 if ( $text === null ) {
460 // The SlotRecord::MAIN role can't be deleted
461 if ( $role === SlotRecord
::MAIN
) {
462 $this->dieWithError( [ 'apierror-compare-maintextrequired', $prefix ] );
465 // These parameters make no sense without text. Reject them to avoid
467 foreach ( [ 'section', 'contentmodel', 'contentformat' ] as $param ) {
468 if ( isset( $params["{$prefix}{$param}-{$role}"] ) ) {
469 $this->dieWithError( [
470 'apierror-compare-notext',
471 wfEscapeWikiText( "{$prefix}{$param}-{$role}" ),
472 wfEscapeWikiText( "{$prefix}text-{$role}" ),
477 $newRev->removeSlot( $role );
481 $model = $params["{$prefix}contentmodel-{$role}"];
482 $format = $params["{$prefix}contentformat-{$role}"];
484 if ( !$model && $rev && $rev->hasSlot( $role ) ) {
485 $model = $rev->getSlot( $role, RevisionRecord
::RAW
)->getModel();
487 if ( !$model && $title && $role === SlotRecord
::MAIN
) {
488 // @todo: Use SlotRoleRegistry and do this for all slots
489 $model = $title->getContentModel();
492 $model = $this->guessModel( $role );
495 $model = CONTENT_MODEL_WIKITEXT
;
496 $this->addWarning( [ 'apiwarn-compare-nocontentmodel', $model ] );
500 $content = ContentHandler
::makeContent( $text, $title, $model, $format );
501 } catch ( MWContentSerializationException
$ex ) {
502 $this->dieWithException( $ex, [
503 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
507 if ( $params["{$prefix}pst"] ) {
509 $this->dieWithError( 'apierror-compare-no-title' );
511 $popts = ParserOptions
::newFromContext( $this->getContext() );
512 $content = $content->preSaveTransform( $title, $this->getUser(), $popts );
515 $section = $params["{$prefix}section-{$role}"];
516 if ( $section !== null && $section !== '' ) {
518 $this->dieWithError( "apierror-compare-no{$prefix}revision" );
520 $oldContent = $rev->getContent( $role, RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
521 if ( !$oldContent ) {
523 [ 'apierror-missingcontent-revid-role', $rev->getId(), wfEscapeWikiText( $role ) ],
527 if ( !$oldContent->getContentHandler()->supportsSections() ) {
528 $this->dieWithError( [ 'apierror-sectionsnotsupported', $content->getModel() ] );
531 $content = $oldContent->replaceSection( $section, $content, '' );
532 } catch ( Exception
$ex ) {
533 // Probably a content model mismatch.
537 $this->dieWithError( [ 'apierror-sectionreplacefailed' ] );
541 // Deprecated 'fromsection'/'tosection'
542 if ( $role === SlotRecord
::MAIN
&& isset( $params["{$prefix}section"] ) ) {
543 $section = $params["{$prefix}section"];
544 $content = $content->getSection( $section );
547 [ "apierror-compare-nosuch{$prefix}section", wfEscapeWikiText( $section ) ],
548 "nosuch{$prefix}section"
553 $newRev->setContent( $role, $content );
555 return [ $newRev, $rev, null ];
559 * Set value fields from a RevisionRecord object
561 * @param array &$vals Result array to set data into
562 * @param string $prefix 'from' or 'to'
563 * @param RevisionRecord|null $rev
565 private function setVals( &$vals, $prefix, $rev ) {
567 $title = $rev->getPageAsLinkTarget();
568 if ( isset( $this->props
['ids'] ) ) {
569 $vals["{$prefix}id"] = $title->getArticleID();
570 $vals["{$prefix}revid"] = $rev->getId();
572 if ( isset( $this->props
['title'] ) ) {
573 ApiQueryBase
::addTitleInfo( $vals, $title, $prefix );
575 if ( isset( $this->props
['size'] ) ) {
576 $vals["{$prefix}size"] = $rev->getSize();
580 if ( $rev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
581 $vals["{$prefix}texthidden"] = true;
585 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
586 $vals["{$prefix}userhidden"] = true;
589 if ( isset( $this->props
['user'] ) ) {
590 $user = $rev->getUser( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
592 $vals["{$prefix}user"] = $user->getName();
593 $vals["{$prefix}userid"] = $user->getId();
597 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
598 $vals["{$prefix}commenthidden"] = true;
601 if ( isset( $this->props
['comment'] ) ||
isset( $this->props
['parsedcomment'] ) ) {
602 $comment = $rev->getComment( RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
603 if ( $comment !== null ) {
604 if ( isset( $this->props
['comment'] ) ) {
605 $vals["{$prefix}comment"] = $comment->text
;
607 $vals["{$prefix}parsedcomment"] = Linker
::formatComment(
608 $comment->text
, Title
::newFromLinkTarget( $title )
614 $this->getMain()->setCacheMode( 'private' );
615 if ( $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
616 $vals["{$prefix}suppressed"] = true;
620 if ( !empty( $rev->isArchive
) ) {
621 $this->getMain()->setCacheMode( 'private' );
622 $vals["{$prefix}archive"] = true;
627 public function getAllowedParams() {
628 $slotRoles = $this->slotRoleRegistry
->getKnownRoles();
629 sort( $slotRoles, SORT_STRING
);
631 // Parameters for the 'from' and 'to' content
635 ApiBase
::PARAM_TYPE
=> 'integer'
638 ApiBase
::PARAM_TYPE
=> 'integer'
642 ApiBase
::PARAM_TYPE
=> $slotRoles,
643 ApiBase
::PARAM_ISMULTI
=> true,
646 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
647 ApiBase
::PARAM_TYPE
=> 'text',
649 'section-{slot}' => [
650 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
651 ApiBase
::PARAM_TYPE
=> 'string',
653 'contentformat-{slot}' => [
654 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
655 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
657 'contentmodel-{slot}' => [
658 ApiBase
::PARAM_TEMPLATE_VARS
=> [ 'slot' => 'slots' ], // fixed below
659 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
664 ApiBase
::PARAM_TYPE
=> 'text',
665 ApiBase
::PARAM_DEPRECATED
=> true,
668 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
669 ApiBase
::PARAM_DEPRECATED
=> true,
672 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
673 ApiBase
::PARAM_DEPRECATED
=> true,
676 ApiBase
::PARAM_DFLT
=> null,
677 ApiBase
::PARAM_DEPRECATED
=> true,
682 foreach ( $fromToParams as $k => $v ) {
683 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
684 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'fromslots';
688 foreach ( $fromToParams as $k => $v ) {
689 if ( isset( $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] ) ) {
690 $v[ApiBase
::PARAM_TEMPLATE_VARS
]['slot'] = 'toslots';
695 $ret = wfArrayInsertAfter(
697 [ 'torelative' => [ ApiBase
::PARAM_TYPE
=> [ 'prev', 'next', 'cur' ], ] ],
702 ApiBase
::PARAM_DFLT
=> 'diff|ids|title',
703 ApiBase
::PARAM_TYPE
=> [
714 ApiBase
::PARAM_ISMULTI
=> true,
715 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
719 ApiBase
::PARAM_TYPE
=> $slotRoles,
720 ApiBase
::PARAM_ISMULTI
=> true,
721 ApiBase
::PARAM_ALL
=> true,
727 protected function getExamplesMessages() {
729 'action=compare&fromrev=1&torev=2'
730 => 'apihelp-compare-example-1',